package com.eyas.software.pattern.eventbus.bus.impl;

import com.eyas.software.pattern.eventbus.bus.EventBus;
import com.eyas.software.pattern.eventbus.dispatcher.Dispatcher;
import com.eyas.software.pattern.eventbus.dispatcher.impl.SyncDispatcher;
import com.eyas.software.pattern.eventbus.event.Event;
import com.eyas.software.pattern.eventbus.register.Register;
import com.eyas.software.pattern.eventbus.register.impl.AnnotationRegister;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;

/**
 * 维护基于@Subscriber注解的注册器，并向注册器内的Subscriber推送事件
 */
public class DefaultEventBus implements EventBus {
    private Register register = new AnnotationRegister();
    private SyncDispatcher dispatcher = new SyncDispatcher();

    @Override
    public void post(Event event) {
        this.dispatcher.dispatch(this.register, event);
    }

    public static DefaultEventBus builder() {
        return new DefaultEventBus();
    }

    /**
     * 根据method的注解注册subscriber和event
     *
     * @param method
     * @return
     */
    public DefaultEventBus register(Method method) {
        return this;
    }

    /**
     * 根据method的注解注销subscriber
     *
     * @param method
     * @return
     */
    public DefaultEventBus unregister(Method method) {
        return this;
    }

    public void destroy() {
        try {
            this.dispatcher.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 测试看看！！！
     *
     * @param args
     * @throws InterruptedException
     * @throws ClassNotFoundException
     */
    public static void main(String[] args) throws InterruptedException, ClassNotFoundException {
        DefaultEventBus eventBus = DefaultEventBus.builder();
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入:");
        String msg = null;
        while ((msg = scanner.nextLine()) != null) {
            if (msg.equals("quit")) {
                break;
            } else {
                String[] msgs = msg.split(",");
                if (msgs[0].equals("int")) {
                    eventBus.post(new Event(int.class, Integer.parseInt(msgs[1])));
                } else {
                    eventBus.post(new Event(String.class, msgs[1].toString()));
                }
                System.out.print("\n请输入:");
            }
        }

        eventBus.destroy();
    }

}
